package workexp.alg.dp;

import org.junit.Test;

/**
 * 爬楼梯
 */
public class ClimbStairs {
    //会超时
    public int climbStairs(int n) {
        if(n==1){
            return 1;
        }else if(n<1){
            return 1;
        }else{
            return climbStairs(n-1)+climbStairs(n-2);
        }
    }

    //备忘录式
    public int climbStairs2(int n) {
        if (n <= 1)
            return 1;
        int[] dp = new int[n + 1];
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }

    //自底向上
    public int climbStairs3(int n) {
        if(n<=2){
            return n;
        }
        //first相当于退两步的状态，second相当于退一步的状态
        int first =1,second=2,sum=0;
        for(int i=3;i<=n;i++){
            sum =first+second;
            first=second;
            second=sum;
        }

        return sum;
    }

    @Test
    public void test(){
        int n = 4;
        int s = climbStairs3(n);
        System.out.println(s);
    }
}
